<template>
  <div>
    <h1>鼠标追踪：{{mouseX}}:{{y}}</h1>
    <p>
      <input type="text" v-model="val" />
      <button @click="handleAdd" style="margin: 0 10px">Add</button>
      <button @click="handleClear">Clear</button>
    </p>
    <ul v-if="list.length">
      <li v-for="(item, index) in list" :key="index" style="margin: 6px 0">
        <input type="checkbox" v-model="item.done" />
        <span :class="{ unDone: item.done }">{{ item.title }}</span>
        <button @click="handleDelete(index)" style="margin: 0 10px">×</button>
      </li>
    </ul>
    <p v-else style="color: red">暂无数据</p>
    <div>
      <span> <input type="checkbox" v-model="allDone" />全选 </span>
      <span>{{ activeLength }} / {{ allLength }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, computed, onMounted } from "vue";

import useMouse from "./composiable/mouse";

interface ListItem {
  title: string;
  done: boolean;
}

// 鼠标追踪
let { x: mouseX, y } = useMouse();

// data
// let val: Ref<string> = ref("");
let val = ref<string>("");
let list = ref<ListItem[]>([
  { title: "吃饭", done: false },
  { title: "睡觉", done: true },
  { title: "玩游戏", done: false },
]);

// computed => 计算属性 get(), set()
// 已完成的任务长度
let activeLength = computed<number>(
  () => list.value.filter((item) => item.done).length
);
// 所有任务的长度
let allLength = computed<number>(() => list.value.length);
// 是否全选
let allDone = computed<boolean>({
  get() {
    return activeLength.value === allLength.value;
  },
  set(value: boolean) {
    list.value.forEach((item) => (item.done = value));
  },
});

// methods
// 添加任务
function handleAdd() {
  list.value.push({ title: val.value, done: false });
  val.value = "";
}
// 删除任务
function handleDelete(index: number) {
  list.value.splice(index, 1);
}
// 清理所有完成的任务
function handleClear() {
  list.value = list.value.filter((item) => !item.done);
}
</script>

<style scoped>
.unDone {
  text-decoration: line-through;
  color: #ccc;
}
</style>
